<?php
class AjaxUserInformer_View_Helper_UserFields extends Zend_View_Helper_Abstract {
	
	public function userFields($subject, $partialStructure) {
		$settings = Engine_Api::_ ()->getApi ( 'settings', 'MsepCore' );
		$user_fields = json_decode ( $settings->ajaxui->user_fields );
		
		if (empty ( $partialStructure )) {
			return '';
		}
		
		if (! ($subject instanceof Core_Model_Item_Abstract) || ! $subject->getIdentity ()) {
			return '';
		}
		
		// Generate
		$content = '';
		$lastContents = '';
		$lastHeadingTitle = null; //Zend_Registry::get('Zend_Translate')->_("Missing heading");
		

		foreach ( $partialStructure as $map ) {
			
			// Get field meta object
			$field = $map->getChild ();
			$value = $field->getValue ( $subject );
			if (! $field || $field->type == 'profile_type' || ! $field->display)
				continue;
			
		// Heading
			if ($field->type == 'heading') {
				if (! empty ( $lastContents )) {
					$content .= $this->_buildLastContents ( $lastContents, $lastHeadingTitle );
					$lastContents = '';
				}
				$lastHeadingTitle = $this->view->translate ( $field->label );
			} 

			// Normal fields
			else {
				if (in_array ( $map->option_id . "_" . $field->field_id, $user_fields )) {
					$tmp = null;
					if ((is_object ( $value ) && isset ( $value->value )) || is_array ( $value )) {
						
						$helper = Engine_Api::_ ()->fields ()->getFieldInfo ( $field->type, 'helper' );
						
						if ($helper) {
							$view = $this->view;
							$view->addHelperPath ( APPLICATION_PATH . '/application/modules/Fields/View/Helper', "Fields_View_Helper" );
							$tmp = $this->view->$helper ( $subject, $field, $value );
						}
					}
					
					if (! empty ( $tmp )) {
						
						$label = $this->view->translate ( $field->label );
						$lastContents .= <<<EOF
            <tr>
            <td style="padding: 3px 10px 3px 0;" valign='top'>{$label}</td>
            <td style="padding: 3px 10px 3px 0;" valign='top'>{$tmp}</td>
            </tr>
EOF;
					
					}
					
					$lastContents .= '';
					$lastContents;
				}
			}
		
		}
		
		if (! empty ( $lastContents )) {
			$content .= $this->_buildLastContents ( $lastContents, $lastHeadingTitle );
		}
		
		return $content;
	}
	
	protected function _buildLastContents($content, $title) {
		if (! $title) {
			return $content;
		}
		
		return <<<EOF
                  <tr>
                  <td style="font-weight: bold; padding: 5px 0; white-space: nowrap;" colspan="2">{$title}</td>
                  </tr>
                  {$content}
EOF;
	}

}